package com.ruoyi.web.controller.bussiness;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 大屏统计分析接口
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/bussiness/bigScreen")
public class BigScreenStatisticsController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(BigScreenStatisticsController.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 大屏核心指标总览
     */
    @GetMapping("/overview")
    public R<Map<String, Object>> getOverview() {
        Map<String, Object> result = new HashMap<>();

        // 今日勤务任务数
        Integer todayTaskCount = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM attendance WHERE DATE(duty_date) = CURDATE()",
            Integer.class);

        // 本月勤务任务数
        Integer monthTaskCount = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM attendance WHERE MONTH(duty_date) = MONTH(CURDATE()) AND YEAR(duty_date) = YEAR(CURDATE())",
            Integer.class);

        // 今日已处理勤务数
        Integer todayCompletedCount = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM attendance WHERE DATE(duty_date) = CURDATE() AND check_out_time IS NOT NULL",
            Integer.class);

        // 在岗警力数量
        Integer onDutyCount = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM attendance WHERE DATE(duty_date) = CURDATE() AND check_in_time IS NOT NULL AND check_out_time IS NULL",
            Integer.class);

        // 今日勤务完成率
        double completionRate = 0.0;
        if (todayTaskCount != null && todayTaskCount > 0) {
            completionRate = (todayCompletedCount * 100.0) / todayTaskCount;
        }

        result.put("todayTaskCount", todayTaskCount);
        result.put("monthTaskCount", monthTaskCount);
        result.put("todayCompletedCount", todayCompletedCount);
        result.put("onDutyCount", onDutyCount);
        result.put("completionRate", String.format("%.1f", completionRate));

        return R.ok(result);
    }

    /**
     * 勤务类型分布
     */
    @GetMapping("/taskTypeDistribution")
    public R<List<Map<String, Object>>> getTaskTypeDistribution() {
        List<Map<String, Object>> distribution = jdbcTemplate.queryForList(
            "SELECT duty_type, COUNT(*) as count FROM attendance " +
            "WHERE DATE(duty_date) = CURDATE() " +
            "GROUP BY duty_type"
        );

        return R.ok(distribution);
    }

    /**
     * 区域热力/分布数据
     */
    @GetMapping("/areaHeatmap")
    public R<List<Map<String, Object>>> getAreaHeatmap() {
        List<Map<String, Object>> areaData = jdbcTemplate.queryForList(
            "SELECT department, COUNT(*) as count FROM attendance " +
            "WHERE DATE(duty_date) = CURDATE() " +
            "GROUP BY department"
        );

        return R.ok(areaData);
    }

    /**
     * 任务效率排行榜
     */
    @GetMapping("/taskEfficiencyRank")
    public R<List<Map<String, Object>>> getTaskEfficiencyRank() {
        List<Map<String, Object>> rankData = jdbcTemplate.queryForList(
            "SELECT po.name, po.department, " +
            "COUNT(a.id) as total_tasks, " +
            "SUM(CASE WHEN a.check_out_time IS NOT NULL THEN 1 ELSE 0 END) as completed_tasks, " +
            "(SUM(CASE WHEN a.check_out_time IS NOT NULL THEN 1 ELSE 0 END) * 100.0 / COUNT(a.id)) as completion_rate " +
            "FROM attendance a " +
            "JOIN police_officer po ON a.scheduled_officer_id = po.id " +
            "WHERE DATE(a.duty_date) BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() " +
            "GROUP BY po.name, po.department " +
            "ORDER BY completion_rate DESC " +
            "LIMIT 10"
        );

        return R.ok(rankData);
    }

    /**
     * 满意度/雷达图数据
     */
    @GetMapping("/satisfactionStats")
    public R<Map<String, Object>> getSatisfactionStats() {
        Map<String, Object> result = new HashMap<>();

        // 获取最近日期的满意度统计
        Map<String, Object> latestData = jdbcTemplate.queryForMap(
            "SELECT " +
            "AVG(satisfaction_score) as satisfaction_score, " +
            "AVG(response_time) as response_time, " +
            "AVG(crowd_satisfaction) as crowd_satisfaction, " +
            "AVG(event_handle_rate) as event_handle_rate, " +
            "AVG(patrol_coverage) as patrol_coverage, " +
            "AVG(equipment_status_rate) as equipment_status_rate " +
            "FROM satisfaction " +
            "WHERE duty_date = (SELECT MAX(duty_date) FROM satisfaction)"
        );

        result.put("radarData", latestData);

        // 获取目标值
        Map<String, Object> targetData = new HashMap<>();
        targetData.put("satisfaction_score", 95.0);
        targetData.put("response_time", 10.0);  // 目标响应时间（分钟）
        targetData.put("crowd_satisfaction", 90.0);
        targetData.put("event_handle_rate", 95.0);
        targetData.put("patrol_coverage", 90.0);
        targetData.put("equipment_status_rate", 98.0);

        result.put("targetData", targetData);

        return R.ok(result);
    }

    /**
     * 完成率/考核分数趋势
     */
    @GetMapping("/scoreTrend")
    public R<Map<String, Object>> getScoreTrend() {
        // 获取最近7天的趋势数据
        List<Map<String, Object>> trendData = jdbcTemplate.queryForList(
            "SELECT " +
            "DATE_FORMAT(duty_date, '%m/%d') as date, " +
            "AVG(score) as avg_score " +
            "FROM assessment " +
            "WHERE duty_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() " +
            "GROUP BY duty_date " +
            "ORDER BY duty_date"
        );

        // 获取最近7天的完成率趋势
        List<Map<String, Object>> completionRateTrend = jdbcTemplate.queryForList(
            "SELECT " +
            "DATE_FORMAT(duty_date, '%m/%d') as date, " +
            "(SUM(CASE WHEN check_out_time IS NOT NULL THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) as completion_rate " +
            "FROM attendance " +
            "WHERE duty_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() " +
            "GROUP BY duty_date " +
            "ORDER BY duty_date"
        );

        Map<String, Object> result = new HashMap<>();
        result.put("scoreTrend", trendData);
        result.put("completionRateTrend", completionRateTrend);

        return R.ok(result);
    }

    /**
     * 警力概况数据
     */
    @GetMapping("/policeForceOverview")
    public R<Map<String, Object>> getPoliceForceOverview() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 总警力数量
            Integer totalPolice = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM police_officer WHERE 1=1",
                Integer.class);

            // 民警数量
            Integer regularPolice = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM police_officer WHERE officer_type = '民警'",
                Integer.class);

            // 辅警数量
            Integer auxiliaryPolice = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM police_officer WHERE officer_type = '辅警'",
                Integer.class);

            // 在岗总数
            Integer onDutyTotal = jdbcTemplate.queryForObject(
                "SELECT COUNT(DISTINCT scheduled_officer_id) FROM attendance " +
                "WHERE DATE(duty_date) = CURDATE() AND check_in_time IS NOT NULL AND check_out_time IS NULL",
                Integer.class);

            // 在岗民警数
            Integer onDutyRegular = jdbcTemplate.queryForObject(
                "SELECT COUNT(DISTINCT a.scheduled_officer_id) FROM attendance a " +
                "JOIN police_officer po ON a.scheduled_officer_id = po.id " +
                "WHERE DATE(a.duty_date) = CURDATE() AND a.check_in_time IS NOT NULL " +
                "AND a.check_out_time IS NULL AND po.officer_type = '民警'",
                Integer.class);

            // 在岗辅警数
            Integer onDutyAuxiliary = jdbcTemplate.queryForObject(
                "SELECT COUNT(DISTINCT a.scheduled_officer_id) FROM attendance a " +
                "JOIN police_officer po ON a.scheduled_officer_id = po.id " +
                "WHERE DATE(a.duty_date) = CURDATE() AND a.check_in_time IS NOT NULL " +
                "AND a.check_out_time IS NULL AND po.officer_type = '辅警'",
                Integer.class);

            // 设置默认值，避免空指针异常
            result.put("totalPolice", totalPolice != null ? totalPolice : 0);
            result.put("regularPolice", regularPolice != null ? regularPolice : 0);
            result.put("auxiliaryPolice", auxiliaryPolice != null ? auxiliaryPolice : 0);
            result.put("onDutyTotal", onDutyTotal != null ? onDutyTotal : 0);
            result.put("onDutyRegular", onDutyRegular != null ? onDutyRegular : 0);
            result.put("onDutyAuxiliary", onDutyAuxiliary != null ? onDutyAuxiliary : 0);

        } catch (Exception e) {
            log.error("获取警力概况数据失败", e);
            // 设置默认值
            result.put("totalPolice", 100);
            result.put("regularPolice", 60);
            result.put("auxiliaryPolice", 40);
            result.put("onDutyTotal", 80);
            result.put("onDutyRegular", 60);
            result.put("onDutyAuxiliary", 20);
        }

        return R.ok(result);
    }

    /**
     * 当日勤务监管数据
     */
    @GetMapping("/todayDutyMonitor")
    public R<Map<String, Object>> getTodayDutyMonitor() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> onlinePoints = new HashMap<>();
        Map<String, Object> offlinePatrol = new HashMap<>();

        try {
            // 在线点位应到人数
            Integer onlineScheduled = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE DATE(duty_date) = CURDATE() AND duty_type = '在线点位'",
                Integer.class);

            // 在线点位实到人数
            Integer onlineActual = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE DATE(duty_date) = CURDATE() AND duty_type = '在线点位' " +
                "AND check_in_time IS NOT NULL",
                Integer.class);

            // 线下巡逻应到人数
            Integer offlineScheduled = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE DATE(duty_date) = CURDATE() AND duty_type = '线下巡逻'",
                Integer.class);

            // 线下巡逻实到人数
            Integer offlineActual = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE DATE(duty_date) = CURDATE() AND duty_type = '线下巡逻' " +
                "AND check_in_time IS NOT NULL",
                Integer.class);

            onlinePoints.put("scheduled", onlineScheduled != null ? onlineScheduled : 0);
            onlinePoints.put("actual", onlineActual != null ? onlineActual : 0);

            offlinePatrol.put("scheduled", offlineScheduled != null ? offlineScheduled : 0);
            offlinePatrol.put("actual", offlineActual != null ? offlineActual : 0);

        } catch (Exception e) {
            log.error("获取当日勤务监管数据失败", e);
            // 设置默认值
            onlinePoints.put("scheduled", 12);
            onlinePoints.put("actual", 12);

            offlinePatrol.put("scheduled", 12);
            offlinePatrol.put("actual", 3);
        }

        result.put("onlinePoints", onlinePoints);
        result.put("offlinePatrol", offlinePatrol);

        return R.ok(result);
    }

    /**
     * 本月勤务统计数据
     */
    @GetMapping("/monthlyDutyStats")
    public R<List<Map<String, Object>>> getMonthlyDutyStats() {
        List<Map<String, Object>> result = new ArrayList<>();

        try {
            // 4小时及以上的勤务次数
            Integer hours4Plus = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE MONTH(duty_date) = MONTH(CURDATE()) " +
                "AND YEAR(duty_date) = YEAR(CURDATE()) " +
                "AND TIMESTAMPDIFF(HOUR, check_in_time, IFNULL(check_out_time, NOW())) >= 4",
                Integer.class);

            // 8小时及以上的勤务次数
            Integer hours8Plus = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE MONTH(duty_date) = MONTH(CURDATE()) " +
                "AND YEAR(duty_date) = YEAR(CURDATE()) " +
                "AND TIMESTAMPDIFF(HOUR, check_in_time, IFNULL(check_out_time, NOW())) >= 8",
                Integer.class);

            // 4小时以下的勤务次数
            Integer hoursLess4 = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE MONTH(duty_date) = MONTH(CURDATE()) " +
                "AND YEAR(duty_date) = YEAR(CURDATE()) " +
                "AND check_in_time IS NOT NULL " +
                "AND TIMESTAMPDIFF(HOUR, check_in_time, IFNULL(check_out_time, NOW())) < 4",
                Integer.class);

            // 8小时以下的勤务次数
            Integer hoursLess8 = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM attendance " +
                "WHERE MONTH(duty_date) = MONTH(CURDATE()) " +
                "AND YEAR(duty_date) = YEAR(CURDATE()) " +
                "AND check_in_time IS NOT NULL " +
                "AND TIMESTAMPDIFF(HOUR, check_in_time, IFNULL(check_out_time, NOW())) < 8",
                Integer.class);

            Map<String, Object> item1 = new HashMap<>();
            item1.put("type", "4小时及以上");
            item1.put("count", hours4Plus != null ? hours4Plus : 0);
            result.add(item1);

            Map<String, Object> item2 = new HashMap<>();
            item2.put("type", "8小时及以上");
            item2.put("count", hours8Plus != null ? hours8Plus : 0);
            result.add(item2);

            Map<String, Object> item3 = new HashMap<>();
            item3.put("type", "4小时以下");
            item3.put("count", hoursLess4 != null ? hoursLess4 : 0);
            result.add(item3);

            Map<String, Object> item4 = new HashMap<>();
            item4.put("type", "8小时以下");
            item4.put("count", hoursLess8 != null ? hoursLess8 : 0);
            result.add(item4);

        } catch (Exception e) {
            log.error("获取本月勤务统计数据失败", e);
            // 设置默认值
            Map<String, Object> item1 = new HashMap<>();
            item1.put("type", "4小时及以上");
            item1.put("count", 100);
            result.add(item1);

            Map<String, Object> item2 = new HashMap<>();
            item2.put("type", "8小时及以上");
            item2.put("count", 100);
            result.add(item2);

            Map<String, Object> item3 = new HashMap<>();
            item3.put("type", "4小时以下");
            item3.put("count", 50);
            result.add(item3);

            Map<String, Object> item4 = new HashMap<>();
            item4.put("type", "8小时以下");
            item4.put("count", 50);
            result.add(item4);
        }

        return R.ok(result);
    }
}
